{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Catastrophic Cancellation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's make two numbers with very similar magnitude:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "x = 1.48234\n",
        "y = 1.48235"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now let's compute their difference in double precision:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "collapsed": false
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "-1.0000000000065512e-05\n"
          ]
        }
      ],
      "source": [
        "x_dbl = np.float64(x)\n",
        "y_dbl = np.float64(y)\n",
        "diff_dbl = x_dbl-y_dbl\n",
        "\n",
        "print(repr(diff_dbl))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "* What would the correct result be?\n",
        "* What has happened here?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "-------------\n",
        "Can you predict what will happen in single precision?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "collapsed": false
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "-1.00136e-05\n"
          ]
        }
      ],
      "source": [
        "x_sng = np.float32(x)\n",
        "y_sng = np.float32(y)\n",
        "diff_sng = x_sng-y_sng\n",
        "\n",
        "print(diff_sng)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.5.0+"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}